package com.music.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.music.biz.OrderBiz;
import com.music.biz.OrderDetailsBiz;
import com.music.biz.ShoppingCartBiz;
import com.music.biz.UserBiz;
import com.music.entity.Order;
import com.music.entity.OrderDetail;
import com.music.entity.ShoppingCart;
import com.music.entity.Tool;
import com.music.entity.User;

@Controller
public class OrderFormController {

	@Autowired
	private ShoppingCartBiz shoppingCartBiz;
	@Autowired
	private OrderBiz orderBiz;
	@Autowired
	private OrderDetailsBiz orderDetailsBiz;
	@Autowired
	private UserBiz UserBiz;

	@RequestMapping("order_confirm")
	public String close(int id, Model model) {
		List<ShoppingCart> shoppingCarts = shoppingCartBiz
				.getShoppingCartsByUserId(id);
		model.addAttribute("shoppingCarts", shoppingCarts);
		int conut = Tool.countSum(shoppingCarts);
		double price = Tool.countPrice(shoppingCarts);
		model.addAttribute("conut", conut);
		model.addAttribute("price", price);
		return "order_confirm";
	}

	@RequestMapping(value = "settleAccounts", method = RequestMethod.POST)
	public String settleAccounts(Order order,int id) {
		List<ShoppingCart> shoppingCarts = shoppingCartBiz
				.getShoppingCartsByUserId(id);
		order.setOrderDate(new Date());
		double sum=0;
		for (ShoppingCart shoppingCart : shoppingCarts) {
			sum+=shoppingCart.getSubtotal();
		}
		order.setTotalPrice(sum);
		order.setUser(UserBiz.getUserById(id));
		order.setDeliveried(0);
		orderBiz.addOrder(order);
		
		List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
		for (ShoppingCart shoppingCart : shoppingCarts) {
			OrderDetail orderDetail =new OrderDetail();
			orderDetail.setOrder(order);
			orderDetail.setAlbum(shoppingCart.getAlbum());
			orderDetail.setQuantity(shoppingCart.getQuantity());
			orderDetailsBiz.addOrderDetail(orderDetail);
		}
		shoppingCartBiz.deleteShoppingCartByuid(order.getUser().getId());
		return "result";
	}
	
	
	

}
